<template>
  <div style="float: left;margin-top: 5px">
    <el-form ref="searchRef" :model="searchFormData">
      <el-form-item label="关键词" >
        <el-input  type="text" v-model="searchFormData.strategyName"></el-input>
      </el-form-item>
    </el-form>
  </div>
  <div style="height: 40px;margin-top: 5px;float: left;margin-left: 20px;">
    <el-button @click="searchClick">查询</el-button>
    <el-button @click="resetSearchClick">重置</el-button>
    <el-button  @click="addClick">新增</el-button>
    <el-button @click="startSchedulingStrategy"  >开启</el-button>
    <el-button @click="stopSchedulingStrategy" >关闭</el-button>
  </div>
  <div style="clear: both"></div>
  <div style="height: calc(100% - 60px);">
    <Table  :show-page="true" ref="tableRef" :show-line-number="true"
            :showCheckBox="false" :url="tableUrl" :columns="columns">
      <template  v-slot:handle="slotProps">
        <el-button  @click.stop="editTableData(slotProps.rowData,slotProps.rowIndex)">编辑</el-button>
        <el-button  @click.stop="deleteTableRowData(slotProps.rowData,slotProps.rowIndex)">删除</el-button>
      </template>
    </Table>
  </div>
  <DialogForm ref="editFormRef" :form="editDialogForm" title="编辑" :data-change="formDataChange" @validateSuccess="validateSuccess">
  </DialogForm>
</template>

<script setup>

import Table from "@/components/plugs/table/Table.vue";
import DialogForm from "@/components/plugs/form/DialogForm.vue";
import {inject, reactive, ref, toRaw} from "vue";
import {FormItemType} from "@/components/plugs/form/DialogFormInterface.ts";
import {AXIOS_NAME} from "@/constant/constant.ts";
import {ElMessage, ElMessageBox} from "element-plus";
import {deleteRow, HandleEnum} from "@/utils/utils.ts";

const tableRef = ref(null);
const $axios = inject(AXIOS_NAME);
const searchRef = ref(null);
const editFormRef = ref(null);
const tableUrl = ref("/scheduling/getPage");

const searchFormData = reactive({
  'strategyName': ''
});

const columns = [
  {field:"strategyName","desc": "策略名称"},
  {field:"strategyType","desc": "策略类型",dicType:"strategy_type"},
  {field:"scheduleType","desc": "调度方式",dicType:"schedule_type"},
  {field:"corn","desc": "调度规则"},
  {field:"hasEnable","desc": "开启状态",dicType:"start_using"},
  {field:"cpuLimit","desc": "cpu限制(%)"},
  {field:"memoryLimit","desc": "内存限制(GB)"},
  {field:"diskLimit","desc": "硬盘限制(GB)"},
  {field:"decisionName","desc": "裁决名称"},
  {field:"priority","desc": "管理容器"},
  {field:"showTime","desc": "创建时间"},
  {field:"handle","desc": "操作",isSlot:true,width:150}
];

let items = [];
items.push({type: FormItemType.INPUT_HIDDEN,name: 'id',label: 'id'});
items.push({type: FormItemType.DIC_SELECT,name: 'strategyType',label: '策略类型',dicType:"strategy_type",defaultValue: '1'});
items.push({type: FormItemType.INPUT_TEXT,name: 'strategyName',label: '策略名称'});
items.push({type: FormItemType.INPUT_NUMBER,name: 'cpuLimit',label: 'cpu限制(%)'});
items.push({type: FormItemType.INPUT_NUMBER,name: 'memoryLimit',label: '内存限制(GB)'});
items.push({type: FormItemType.INPUT_NUMBER,name: 'diskLimit',label: '硬盘限制(GB)'});
items.push({type: FormItemType.INPUT_TEXT,name: 'decisionName',label: '裁决名称',hasShow: false});
items.push({type: FormItemType.DIC_SELECT,name: 'scheduleType',label: '调度方式',dicType:"schedule_type",defaultValue: '1'});
items.push({type: FormItemType.INPUT_TEXT,name: 'corn',label: '调度规则'});
items.push({type: FormItemType.CUSTOMIZE_SELECT,label: '管理容器',name: 'containerIds',
  url: '/deploy/getDeployedContainerList',textFiled:'containerName',valueField: "id",isMultiple:true});
let editDialogForm = reactive({
  splitCol: 1,
  gutter: 20,
  labelWidth: 115,
  items:items,
  rules:{},
});

const searchClick = () =>{
  tableRef.value.reload(toRaw(searchFormData));
}

const resetSearchClick = () =>{
  for(const  key in searchFormData){
    searchFormData[key] = '';
  }
}

const stopSchedulingStrategy = () => {
  let checkedData = tableRef.value.getCheckedData();
  if(checkedData.length <= 0){
    ElMessage.error("请选择一条数据!");
    return;
  }
  ElMessageBox.confirm(
      '是否关闭策略?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    $axios.post("/scheduling/stopScheduling",checkedData[0]).then(response => {
      const data = response.data;
      if(data.code != 1){
        ElMessage.error("操作失败!");
        return;
      }
      ElMessage.info("操作成功!");
      tableRef.value.reload();
    });
  });
}

const startSchedulingStrategy = () => {
  let checkedData = tableRef.value.getCheckedData();
  if(checkedData.length <= 0){
    ElMessage.error("请选择一条数据!");
    return;
  }
  ElMessageBox.confirm(
      '是否开启策略?','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    $axios.post("/scheduling/startScheduling",checkedData[0]).then(response => {
      const data = response.data;
      if(data.code != 1){
        ElMessage.error("操作失败!");
        return;
      }
      ElMessage.info("操作成功!");
      tableRef.value.reload();
    });
  });
}

const addClick = () =>{
  editFormRef.value.show();
}

const editTableData = (rowData,rowIndex) =>{
  rowData.containerIds = rowData.containerIds == undefined ? [] : rowData.containerIds.split(",");
  editFormRef.value.show();
  editFormRef.value.setData(rowData);
}

const deleteTableRowData = (rowData,rowIndex) =>{
  deleteRow('/scheduling/delete',rowData,function (state,data){
    if(state == HandleEnum.SUCCESS){
      tableRef.value.reload();
    }
  });
}

const validateSuccess = (data) =>{
  data.containerIds = data.containerIds != null ? JSON.stringify(data.containerIds) : data.containerIds;
  $axios.post('/scheduling/addOrUpdate',data).then(response => {
    const data = response.data;
    if(data.code == 1){
      tableRef.value.reload();
      editFormRef.value.close();
      ElMessage.info("操作成功！");
      return;
    }
    ElMessage.error(data.msg);
  },error =>{

  });
}

const formDataChange = (oldValue,newValue,field) =>{
  if(field != 'strategyType' && 'scheduleType' != field){
    return;
  }
  let formData = editFormRef.value.getFormData();
  editFormRef.value.triggerAllField(true);
  if('1' == formData.strategyType){
    editFormRef.value.triggerField(['decisionName'],false);
  }else if('2' == formData.strategyType){
    editFormRef.value.triggerField(['cpuLimit','memoryLimit','diskLimit'],false);
  }else if('3' == formData.strategyType){
    editFormRef.value.triggerField(['decisionName'],false);
  }
  if("2" == formData.scheduleType){
    editFormRef.value.triggerField(['corn'],false);
  }
}

</script>

<style scoped>

</style>